﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util;
using PlanningGIS.Util.Serialization;
using System.IO;
using System.Threading.Tasks;
using PlanningGIS.MetaData;
using PlanningGIS.Util.Data;

namespace PlanningGIS.Product
{
    /// <summary>
    /// 设置当前数据表的规则
    /// </summary>
    public partial class FrmMetaRule : Office2007Form
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="tablename">数据表名称</param>
        /// <param name="selFields">字段信息</param>
        public FrmMetaRule(string tablename, List<MetaField> selFields)
        {
            InitializeComponent();
            Init();
            _tablename = tablename;
            SelFields = selFields;
        }

        /// <summary>
        /// 数据表名称
        /// </summary>
        private string _tablename = "";

        /// <summary>
        /// 选择的字段
        /// </summary>
        public List<MetaField> SelFields { get; private set; }

        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmSetField_Load(object sender, EventArgs e)
        {
            AddRows();
        }

        /// <summary>
        /// 初始化数据信息
        /// </summary>
        private void Init()
        {
            dgrdvwcolValue.ValueMember = "Value";
            dgrdvwcolValue.DisplayMember = "Name";
            Array arr = Enum.GetValues(typeof(zjgisAutoValueType));
            List<ValueName> types = new List<ValueName>();
            int count = arr.Length;
            for (int i = 0; i < count; i++)
            {
                zjgisAutoValueType t = (zjgisAutoValueType)arr.GetValue(i);
                types.Add(new ValueName()
                {
                    Name = t.GetDescription(),
                    Value = t.ToString()
                });
            };
            dgrdvwcolValue.DataSource = types;
        }
       
        /// <summary>
        /// 设置为默认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetDefault_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                List<MetaRule> rs = null;
                if (!File.Exists(ProductHelper.MetaRulePath))
                    rs = new List<MetaRule>();
                else
                    rs = (List<MetaRule>)XmlSerialization.Deserialize<List<MetaRule>>(ProductHelper.MetaRulePath, null);
                MetaRule tmpr = rs.FirstOrDefault(t => t.TableName.Equals(_tablename, StringComparison.CurrentCultureIgnoreCase));
                if (tmpr == null)
                {
                    tmpr = new MetaRule()
                    {
                        TableName = _tablename,
                    };
                    rs.Add(tmpr);
                }
                tmpr.Fields = SetMetaRule();
                XmlSerialization.Serialize<List<MetaRule>>(ProductHelper.MetaRulePath, rs, null);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 从默认读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetDefault_Click(object sender, EventArgs e)
        {
            if (!File.Exists(ProductHelper.MetaRulePath))
            {
                MsgHelper.ShowInfomationMsgbox("没有默认的规则信息，不能恢复默认");
                return;
            }
            try
            {
                this.Cursor = Cursors.WaitCursor;
                List<MetaRule> rs = (List<MetaRule>)XmlSerialization.Deserialize<List<MetaRule>>(ProductHelper.MetaRulePath, null);
                MetaRule tmpr = rs.FirstOrDefault(t => t.TableName.Equals(_tablename, StringComparison.CurrentCultureIgnoreCase));
                if (tmpr == null) return;
                AddRows(tmpr.Fields);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fields"></param>
        private void AddRows(List<MetaField> fields = null)
        {
            dgrdvwFields.Rows.Clear();
            if (SelFields == null || SelFields.Count == 0) return;
            foreach (MetaField f in SelFields)
            {
                int idx = dgrdvwFields.Rows.Add(new object[] { f.Name, f.Alias, f.FieldType, f.Visible, f.AllowNull, f.AutoValueType.ToString() });
                if (fields == null || fields.Count == 0) continue;
                MetaField m = fields.FirstOrDefault(t => t.Name.Equals(f.Name, StringComparison.CurrentCultureIgnoreCase));
                if (m == null || string.IsNullOrWhiteSpace(m.Name)) continue;
                dgrdvwFields.Rows[idx].Cells[dgrdvwcolAlias.Index].Value = m.Alias;
                dgrdvwFields.Rows[idx].Cells[dgrdvwcolFieldType.Index].Value = m.FieldType;
                dgrdvwFields.Rows[idx].Cells[dgrdvwcolVisible.Index].Value = m.Visible;
                dgrdvwFields.Rows[idx].Cells[dgrdvwcolAllowNull.Index].Value = m.AllowNull;
                dgrdvwFields.Rows[idx].Cells[dgrdvwcolValue.Index].Value = m.AutoValueType.ToString();
            }
        }

        /// <summary>
        /// 设置元数据表字段规则
        /// </summary>
        private List<MetaField> SetMetaRule()
        {
            List<MetaField> fields = new List<MetaField>();
            foreach (DataGridViewRow row in dgrdvwFields.Rows)
            {
                zjgisAutoValueType v = zjgisAutoValueType.zjgisAutoValueUnKnow;
                object obj = row.Cells[dgrdvwcolValue.Index].Value;
                if (obj != null && !string.IsNullOrEmpty(obj.ToString()))
                    v = (zjgisAutoValueType)Enum.Parse(typeof(zjgisAutoValueType), obj.ToString());
                string name = row.Cells[dgrdvwcolName.Index].Value.ToString().Trim();
                if (ProductHelper.FilterFields.Exists(t => t.Equals(name, StringComparison.CurrentCultureIgnoreCase))) continue;
                MetaField fd=new MetaField()
                {
                    Name = name,
                    Alias = row.Cells[dgrdvwcolAlias.Index].Value.ToString(),
                    FieldType = row.Cells[dgrdvwcolFieldType.Index].Value == null ? "String" : row.Cells[dgrdvwcolFieldType.Index].Value.ToString(),
                    AllowNull = (bool)row.Cells[dgrdvwcolAllowNull.Index].Value,
                    Visible = (bool)row.Cells[dgrdvwcolVisible.Index].Value,
                    AutoValueType = v
                };
                if (fd.Name.EndsWith("日期")) fd.FieldType = "DataTime";
                fields.Add(fd);
            }
            return fields;
        }
        
        /// <summary>
        /// 单击列标题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrdvwFields_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == dgrdvwcolVisible.Index)
            {
                if (dgrdvwcolVisible.Tag == null || dgrdvwcolVisible.Tag.ToString() == "1")
                {
                    SetCheck(1, e.ColumnIndex);
                    dgrdvwcolVisible.Tag = 2;
                }
                else
                {
                    SetCheck(2, e.ColumnIndex);
                    dgrdvwcolVisible.Tag = 1;
                }
            }
            else if (e.ColumnIndex == dgrdvwcolAllowNull.Index)
            {
                if (dgrdvwcolAllowNull.Tag == null || dgrdvwcolAllowNull.Tag.ToString() == "1")
                {
                    SetCheck(1, e.ColumnIndex);
                    dgrdvwcolAllowNull.Tag = 2;
                }
                else
                {
                    SetCheck(2, e.ColumnIndex);
                    dgrdvwcolAllowNull.Tag = 1;
                }
            }
        }

        /// <summary>
        /// 设置选中状态
        /// </summary>
        /// <param name="optype">1：全选；2：全不选；3：反选</param>
        /// <param name="colindex"></param>
        private void SetCheck(int optype, int colindex)
        {
            if (dgrdvwFields.Rows.Count == 0) return;
            foreach (DataGridViewRow row in dgrdvwFields.Rows)
            {
                switch (optype)
                {
                    case 1:
                        row.Cells[colindex].Value = true;
                        break;
                    case 2:
                        row.Cells[colindex].Value = false;
                        break;
                    case 3:
                        row.Cells[colindex].Value = !((bool)row.Cells[colindex].Value);
                        break;
                }
            }
        }

        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            SelFields = SetMetaRule();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
